package com.ssd4.uidesign.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BaseDao {
	private  Connection conn=null;
	private  PreparedStatement pstmt=null;
	private  ResultSet rs=null;
	private void getConnection()
	{
		conn=DBConnectionManager.getConnection();
	}
	
	/*
	 *@author: yjhxdzyx;
	 *@date 2013-9-22 下午10:21:34
	 *@function 使用PreparedStatement执行查询SQL语句(带参数)
	 *@param sql
	 *String 要执行的SQL语句
	 *Object[] SQL参数列表
	 *@return ResultSet 查询结果集
	 *@throws Exception
	 */
	public ResultSet executePreparedStatementQuery(String sql, Object paras[])
			throws Exception {
		try {
			getConnection();
			pstmt = conn.prepareStatement(sql);
			this.setPreparedStatementParas(pstmt, paras);
			rs = pstmt.executeQuery();
			return rs;
		} catch (SQLException ex) {
			throw new Exception("** Error in executeQuery():" + ex.getMessage()
					+ "**", ex);
		}

	}
	
	/*
	 *@author: yjhxdzyx;
	 *@date 2013-9-22 下午10:23:02
	 *@function 使用执行更新SQL语句(带参数)
	 *@param sql
	 *String 要执行的SQL语句
	 *@param paras
	 *Object[] SQL参数列表
	 *@throws Exception
	 */
	public int executePreparedStatementUpdate(String sql, Object[] paras)
			throws Exception {
		int count = 0;
		try {
			getConnection();
			pstmt = conn.prepareStatement(sql);
			this.setPreparedStatementParas(pstmt, paras);
			count = pstmt.executeUpdate();
			
		} catch (SQLException ex) {
			throw new Exception("** Error in executeUpdate():"
					+ ex.getMessage() + "**", ex);
		}
		return count;
	}
	
	/*
	 *@author: yjhxdzyx;
	 *@date 2013-9-22 下午10:23:57
	 *@function 实现Object数组表示的参数列表和SQL语句中的"?"绑定
	 *@param pstmt
	 *PreparedStatement
	 *@param paras
	 *Object[]
	 *@throws SQLException
	 */
	private void setPreparedStatementParas(PreparedStatement pstmt,	Object[] paras) throws SQLException {
		if (paras != null && paras.length > 0) {
			for (int i = 0; i < paras.length; i++) {
				if (paras[i] == null) {
					// 注意，SQL不支持java.sql.Types.NULL，所以使用java.sql.Types.VARCHAR代替
					pstmt.setNull(i + 1, java.sql.Types.VARCHAR);
				} else {
					// begin from index 1
					pstmt.setObject(i + 1, paras[i]);
				}
			}
		}
	}
	
	/*
	 *@author: yjhxdzyx;
	 *@date 2013-9-22 下午10:24:54
	 *@function 关闭连接
	 */
	public void closeAll() {
		try {
			
		 if(rs!=null){
			    	try {
						rs.close();
					} catch (SQLException e) {
						System.out.println("closeAll()+原因"+e.getMessage());
					}
			    }
		  if(pstmt!=null){
			    	try {
						pstmt.close();
					} catch (SQLException e) {
						System.out.println("closeAll()+原因"+e.getMessage());
					}
			    }
		  if(conn!=null)
			{
				conn.close();
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}